package org.jackie.tomcat.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * HttpServer
 *
 * @author Jackie Hou
 * @date 2023/12/12 17:11
 * @version 1.0
 */
public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await(8080);
    }

    /**
     * 服务器循环等待并执行请求
     *
     * @param port 端口号
     */
    public void await(int port) {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (true) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;

            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                //构造request
                Request request = new Request(input);
                request.parse();

                //构造response
                Response response = new Response(output);
                response.setRequest(request);
                response.sendStaticResource();

                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
